<?php

class SaleController extends Controller
{

	/**
     * 过滤器
	 * @return 返回值是一个存放过滤器的数组
	 */
	public function filters()
	{
		return array(
            'accessAuth',//自定义授权方式
			//'accessControl', //默认授权方式
			'postOnly + delete',//删除操作只支持post请求
		);
	}
    /**
     * 自定义权限验证规则
     * @param type $filterChain
     * @throws CHttpException
     */
    public function filterAccessAuth($filterChain) {  
        if(Yii::app()->user->getIsGuest()) {  
            echo '<script>top.location.href="'.Yii::app()->user->returnUrl.'";</script>';
            exit;
        } else if(!Yii::app()->user->getIsGuest() && !in_array($this->getAction()->getId(), $this->authlessActions())){
            throw new CHttpException(403,'无权访问此页面');
        }
        $filterChain->run();  
    }  
    /**
     * 页面白名单
     * @return type
     */
    public function authlessActions(){  
        return array(
            'index','admin','view','create','update','delete','party','partyMsg','adminClander',
            'partyClander','upload','export'
	); 
    }

	/**
	 * 查看页面
	 * @param integer $id
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * 添加页面
	 * 如果添加成功，跳转到查看页面
	 */
	public function actionCreate()
	{
		$model=new Sale;

		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);

		if(isset($_POST['Sale']))
		{
			$model->attributes=$_POST['Sale'];
			if($model->save()){
                            Yii::app()->user->setFlash('success','操作成功！');
                            $this->redirect(array('Sale/admin'));
                        }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
        /**
	 * 添加页面
	 * 如果添加成功，跳转到查看页面
	 */
	public function actionUpload()
	{
		$model=new Sale;
               if(isset($_POST['userfile']))
                {
//                   $transaction = Yii::app()->db->beginTransaction(); //创建事务
                  if(!empty($_POST['userfile'])){
                    $path=$_POST['userfile'];
                    $len=strlen($path);
//                  $index=strpos($path,'/',2);
                    $index=strpos($path,'/',4);
                    
                    $path=substr($path,$index+1,$len);
                    include_once(dirname(dirname(__FILE__)).'/extensions/PHPExcel/PHPExcel/IOFactory.php');  
                    $reader = PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文件
                    $PHPExcel = PHPExcel_IOFactory::load($path);
                     
                    $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表(编号从 0 开始)  
                    $highestRow = $sheet->getHighestRow(); // 取得总行数  
                    $highestColumn  = $sheet->getHighestColumn(); // 取得总列数  
                    $transaction = Yii::app()->db->beginTransaction(); //创建事务
                        for ($row = 2; $row <= $highestRow; $row++) { 
                            $data = array();
                            for ($column = 0; $column <= 12; $column++){  
                                $val = $sheet->getCellByColumnAndRow($column, $row)->getValue(); 
        //                        $val = iconv("utf-8","gbk",$val);
                                $data[$column]=$val;
                            }

                            $sale=new Sale();
                            if(!empty($data[0])){
                                $party=Party::model()->find("user_code='".$data[0]."'");
                                //有一条记录的用户识别码不对，全部回滚
                                 if(empty($party)){
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die(); 
                                 }
                                $sale->party_id=$party->id;
                               
                                $sale->order_number=$data[1];
                                $sale->product_name=$data[2];
                                $sale->bar=$data[3];
                                $sale->goods_number=$data[4];
                                $sale->discount=$data[5];
                                $sale->add_time=$data[6];
                                $sale->price=$data[7];
                                $sale->sale_count=$data[8];
                                $sale->amount=$data[9];
//                              $sale->integral_qty=$data[10];
                                $sale->integral_type=$data[10];
                                $sale->integral_qty=floor($sale->amount);

                                if($sale->save()){}
                                else{    
                                   $transaction->rollback(); //回滚事务
                                   Yii::app()->end();
                                   die(); 
                                }
                            }
                          
                    }  
                  }

                       $transaction->commit(); //提交事务
                       Yii::app()->user->setFlash('success','操作成功！');
                        $this->redirect(array('sale/admin'));  
		}

		$this->render('upload',array(
			'model'=>$model,
		));
	}

	/**
	 * 修改页面
	 * 如果修改成功，跳转到查看页面
	 * @param integer $id 
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);

		if(isset($_POST['Sale']))
		{
			$model->attributes=$_POST['Sale'];
			if($model->save()){
                            Yii::app()->user->setFlash('success','操作成功！');
                            $this->redirect(array('Sale/admin'));
                        }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * 删除功能
	 * 一般只接受post方式的异步提交
	 * @param integer $id 
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
            $id=$_POST['id'];
            //获取id数组批量删除
            $criteria= new CDbCriteria;
            $criteria->addInCondition('id', $id);
            $res=Sale::model()->deleteAll($criteria);
            //输出json结果
            echo CJSON::encode(array('result'=>$res));
        }else{
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } 
	}

	/**
	 * 列表页
	 */
	public function actionAdmin()
	{
		$model=new Sale('search');
		$model->unsetAttributes();  //清空并初始化
		if(isset($_GET['Sale']))
			$model->attributes=$_GET['Sale'];
                if(isset($_GET['detail_id'])){
                      $party_id=$_GET['detail_id'];
//                    $party_ids =array();
//                    $detail_id=$_GET['detail_id'];
//                    $party=Party::model()->findAll('ad_id='.$detail_id);
//                    $i=0;
//                    foreach ($party as $value) {
//                        $party_ids[$i]=$value->id;
//                        $i++;
//                    }
                    $this->render('admin',array(
                            'model'=>$model,
                            'data'=>$model->search_clander($party_id),
                    ));     
                    return;
                }
                if(isset($_GET['ad_id'])){
                    $party_ids =array();
                    $ad_id=$_GET['ad_id'];
                    $party=Party::model()->findAll('ad_id='.$ad_id);
                    $i=0;
                    foreach ($party as $value) {
                        $party_ids[$i]=$value->id;
                        $i++;
                    }
                    $this->render('admin',array(
                            'model'=>$model,
                            'data'=>$model->search_clander($party_ids),
                    ));     
                    return;
                }
                if(isset($_GET['id'])){
                    $party_id=$_GET['id'];
                    $party_sale=Party::model()->findByPk($party_id);
                    $model->party_id=$party_sale->user_code;
                }
		$this->render('admin',array(
			'model'=>$model,
			'data'=>$model->search(),
		));
	}
	/**
	 * 列表页
	 */
	public function actionAdminClander()
	{
		$model=new Sale('search');
		$model->unsetAttributes();  //清空并初始化
		if(isset($_GET['Sale']))
			$model->attributes=$_GET['Sale'];
                if(isset($_GET['detail_id'])){
                    $party_id=$_GET['detail_id'];
                    $this->render('adminClander',array(
                            'model'=>$model,
                            'data'=>$model->search_clander($party_id),
                    ));     
                    return;
                }
                if(isset($_GET['ad_id'])){
                    $party_ids =array();
                    $ad_id=$_GET['ad_id'];
                    $party=Party::model()->findAll('ad_id='.$ad_id);
                    $i=0;
                    foreach ($party as $value) {
                        $party_ids[$i]=$value->id;
                        $i++;
                    }
                    $this->render('adminClander',array(
                            'model'=>$model,
                            'data'=>$model->search_clander($party_ids),
                    ));     
                    return;
                }  
                $clander_id=0;
                if(isset($_GET['id'])){
                    $party_id=$_GET['id'];
                    $clander_id=$_GET['clander_id'];
                    $party_sale=Party::model()->findByPk($party_id);
                    $model->party_id=$party_sale->user_code;
                }
		$this->render('adminClander',array(
			'model'=>$model,
                        'clander_id'=>$clander_id,
			'data'=>$model->search(),
		));
	}        
        public function actionParty()
	{
		$model=new Sale('search');
		$model->unsetAttributes();  //清空并初始化
		if(isset($_GET['Sale']))
			$model->attributes=$_GET['Sale'];
                if(isset($_GET['detail_id'])){
                    $party_ids =array();
                    $detail_id=$_GET['detail_id'];
                    $party=Party::model()->findAll('ad_id='.$detail_id);
                    $i=0;
                    foreach ($party as $value) {
                        $party_ids[$i]=$value->id;
                        $i++;
                    }
                    $this->render('party',array(
                            'model'=>$model,
                            'data'=>$model->search_groups($party_ids),
                    ));     
                    return;
                }
		$this->render('party',array(
			'model'=>$model,
			'data'=>$model->search_group(),
		));
	}
        public function actionPartyClander()
	{
		$model=new Sale('search');
		$model->unsetAttributes();  //清空并初始化
		if(isset($_GET['Sale']))
			$model->attributes=$_GET['Sale'];
                if(isset($_GET['detail_id'])){
                    $party_ids =array();
                    $detail_id=$_GET['detail_id'];
                    $party=Party::model()->findAll('ad_id='.$detail_id);
                    $i=0;
                    foreach ($party as $value) {
                        $party_ids[$i]=$value->id;
                        $i++;
                    }
                    $this->render('partyClander',array(
                            'model'=>$model,
                            'clander_id'=>$detail_id,
                            'data'=>$model->search_groups($party_ids),
                    ));     
                    return;
                }
		$this->render('partyClander',array(
			'model'=>$model,
			'data'=>$model->search_group(),
		));
	}
        
        public function actionPartyMsg()
	{
		$model=new Sale('search');
		$model->unsetAttributes();  //清空并初始化
                $party_id=0;
                if(isset($_GET['party_id'])){
                    $party_id=$_GET['party_id'];
                }
		$this->render('partyMsg',array(
			'model'=>$model,
			'data'=>$model->search_party($party_id),
		));
	}        

        /**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Sale the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Sale::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
        /**
         * 导出excel
         */
        public function actionExport(){
            $model=new Sale('search');
            $model->unsetAttributes();  //清空并初始化
            if(isset($_GET['Sale']))
		$model->attributes=$_GET['Sale'];
//            if(!empty($_GET['id'])){
                //导出excel
                include_once(dirname(dirname(__FILE__)).'/extensions/PHPExcel/PHPExcel/IOFactory.php');  
                $phpexcel = new PHPExcel();
                $phpexcel->setActiveSheetIndex(0);
                $phpactiveSheet = $phpexcel->getActiveSheet();
                $phpactiveSheet -> setTitle("消费记录");
                $phpactiveSheet -> setCellValue("A1","积分名称");
                $phpactiveSheet -> setCellValue("B1","积分数量");
                $phpactiveSheet -> setCellValue("C1","用户手机号");
//                $phpactiveSheet -> setCellValue("D1","商品名");     
//                $phpactiveSheet -> setCellValue("E1","条形码");
//                $phpactiveSheet -> setCellValue("F1","货号");
//                $phpactiveSheet -> setCellValue("G1","折扣率");
//                $phpactiveSheet -> setCellValue("H1","消费时间");
//                $phpactiveSheet -> setCellValue("I1","单价");
//                $phpactiveSheet -> setCellValue("J1","数量");
//                $phpactiveSheet -> setCellValue("K1","总金额");
//                $phpactiveSheet -> setCellValue("L1","积分数量");
//                $phpactiveSheet -> setCellValue("M1","积分类型");
                
//                $id=$_GET['id'];
//                $id_array=explode(',',$id);
//                //获取id数组批量删除
//                $criteria= new CDbCriteria;
//                $criteria->addInCondition('id', $id_array);
//                $data= Sale::model()->with('party')->findAll("party.user_code like'%".$model->party_id."%'");
                $data=$model->search_export();               
                $index=2;
                foreach ($data as $value){
                    $phpactiveSheet -> setCellValue("A".$index,$value->integral_type);
                    $phpactiveSheet -> setCellValue("B".$index,$value->integral_qty);
                    $phpactiveSheet -> setCellValue("C".$index,$value->phone);
//                    $phpactiveSheet -> setCellValue("D".$index,$value->product_name);     
//                    $phpactiveSheet -> setCellValue("E".$index,$value->bar);
//                    $phpactiveSheet -> setCellValue("F".$index,$value->goods_number);
//                    $phpactiveSheet -> setCellValue("G".$index,$value->discount);
//                    $phpactiveSheet -> setCellValue("H".$index,$value->add_time);
//                    $phpactiveSheet -> setCellValue("I".$index,$value->price);
//                    $phpactiveSheet -> setCellValue("J".$index,$value->sale_count);
//                    $phpactiveSheet -> setCellValue("K".$index,$value->amount);
//                    $phpactiveSheet -> setCellValue("L".$index,Sale::model()->getTotalsQty($value->party_id));
//                    $phpactiveSheet -> setCellValue("M".$index,$value->integral_type);
                    $index++;
                }
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="sale'.time().'.xls"');
                header('Cache-Control: max-age=0');
                $objWriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
                $objWriter->save('php://output');
                exit;
//                echo CJSON::encode(array('result'=>0)); 
                
//            }else{
//                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
//            }             
//                $phpexcel = new PHPExcel();
//                $phpexcel->setActiveSheetIndex(0);
//                $phpactiveSheet = $phpexcel->getActiveSheet();
//                $phpactiveSheet -> setTitle("消费记录");
//                $phpactiveSheet -> setCellValue("A1","序号");
//                $phpactiveSheet -> setCellValue("B1","用户识别码");
//                $phpactiveSheet -> setCellValue("C1","订单号");
//                $phpactiveSheet -> setCellValue("D1","商品名");     
//                $phpactiveSheet -> setCellValue("E1","条形码");
//                $phpactiveSheet -> setCellValue("F1","货号");
//                $phpactiveSheet -> setCellValue("G1","折扣率");
//                $phpactiveSheet -> setCellValue("H1","消费时间");
//                $phpactiveSheet -> setCellValue("I1","单价");
//                $phpactiveSheet -> setCellValue("J1","数量");
//                $phpactiveSheet -> setCellValue("K1","总金额");
//                $phpactiveSheet -> setCellValue("L1","积分数量");
//                $phpactiveSheet -> setCellValue("M1","积分类型");
//                $model= Sale::model()->findAll();
//                $index=2;
//                foreach ($model as $value){
//                    $phpactiveSheet -> setCellValue("A".$index,$value->id);
//                    $phpactiveSheet -> setCellValue("B".$index,$value->party->user_code);
//                    $phpactiveSheet -> setCellValue("C".$index,$value->order_number);
//                    $phpactiveSheet -> setCellValue("D".$index,$value->product_name);     
//                    $phpactiveSheet -> setCellValue("E".$index,$value->bar);
//                    $phpactiveSheet -> setCellValue("F".$index,$value->goods_number);
//                    $phpactiveSheet -> setCellValue("G".$index,$value->discount);
//                    $phpactiveSheet -> setCellValue("H".$index,$value->add_time);
//                    $phpactiveSheet -> setCellValue("I".$index,$value->price);
//                    $phpactiveSheet -> setCellValue("J".$index,$value->sale_count);
//                    $phpactiveSheet -> setCellValue("K".$index,$value->amount);
//                    $phpactiveSheet -> setCellValue("L".$index,$value->integral_qty);
//                    $phpactiveSheet -> setCellValue("M".$index,$value->integral_type);
//                    $index++;
//                }
//                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//                header('Content-Disposition: attachment;filename="sale'.time().'.xls"');
//                header('Cache-Control: max-age=0');
//                $objWriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
//                $objWriter->save('php://output');
//                exit;            
        }

        /**
	 * Performs the AJAX validation.
	 * @param Sale $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='sale-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
